import mongoose from '../config/DBHelpler'
import moment from 'moment'
import { getTempName } from '@/common/Utils'

const Schema = mongoose.Schema

const UserSchema = new mongoose.Schema(
  {
    username: { type: String, index: { unique: true }, sparse: true },
    name: String,
    password: String,
    // created: Date,
    // updated: Date,
    favs: { type: Number, default: 100 },
    gender: { type: String, default: '' },
    roles: { type: Array, default: ['user'] },
    pic: { type: String, default: 'http://localhost:3000/images/avatar/1.jpg' },
    mobile: { type: String, default: '', match: /^1[3-9](\d{9})$/ },
    status: { type: String, default: '0' },
    regmark: { type: String, default: '' },
    location: { type: String, default: '' },
    isVip: { type: String, default: '0' },
    count: { type: Number, default: 0 },
    openId: { type: String, default: '' },
    unionId: { type: String, default: '' },
  },
  { timestamps: { createdAt: 'created', updatedAt: 'updated' } }
)
UserSchema.pre('save', function (next) {
  this.created = moment().format('YYYY-MM-DD HH:mm:ss')
  next()
})
UserSchema.pre('update', function (next) {
  this.update = moment().format('YYYY-MM-DD HH:mm:ss')
  next()
})
UserSchema.post('save', function (err, doc, next) {
  if (err.name === 'MongoError' && err.code === 11000) {
    next(new Error('Error: Monngose has a duplicate key.'))
  } else {
    next(err)
  }
})

UserSchema.statics = {
  findByID: function (id) {
    return this.findOne(
      { _id: id },
      {
        password: 0,
        username: 0,
        mobile: 0,
      }
    )
  },
  deleteall: function (arr) {
    return this.remove({ _id: { $in: arr } })
  },
  findorcreatedByOpenData: function (wxuserInfo) {
    return this.findOne(
      { openId: wxuserInfo.openId },
      { unionId: 0, password: 0, openId: 0 }
    ).then((user) => {
      return (
        user ||
        this.create({
          openId: wxuserInfo.openId,
          unionId: wxuserInfo.unionId,
          username: getTempName(), //随机邮箱
          name: wxuserInfo.nickName,
          gender: wxuserInfo.gender,
          pic: wxuserInfo.avatarUrl,
          location: wxuserInfo.city,
        })
      )
    })
  },
}
const UserModel = mongoose.model('users', UserSchema)

export default UserModel
